import os.path
import numpy as np
from pycwr.io import read_auto
from scipy.interpolate import griddata
from utils.Logger import get_logger

logger = get_logger()  # 配置日志


class Radar(object):
    def __init__(self, load_path, save_path, currentName):
        '''

        :param load_path: 基数据存放的路径位置和文件名称的拼接
        :param save_path:保存的路径
        '''

        self.lon_min = 113.5
        self.lon_max = 115.5
        self.lat_min = 37.0
        self.lat_max = 39.0
        self.load_path = load_path
        self.grid_size = 400  # 栅格大小  默认为400
        self.save_path = save_path
        self.filename = currentName  # 保存的名称只有对应的年月日.npy
        self.dbz_data = self.prePareData()

    def getName(self):
        filename = self.load_path.split("/")[-1]
        time_str = filename.split('_')[4]  # 获取时间部分
        time_str = time_str[:12]
        return time_str
        # 解析原始的雷达基数据并且将其保存为npy

    def prePareData(self):
        ds = read_auto(self.load_path).fields[0]
        subset = ds.where((ds.lon >= self.lon_min) & (ds.lon <= self.lon_max) &
                          (ds.lat >= self.lat_min) & (ds.lat <= self.lat_max),
                          drop=True)
        lon = subset.lon.values.flatten()
        lat = subset.lat.values.flatten()
        dbz = subset.dBZ.values.flatten()
        lon_grid, lat_grid = np.meshgrid(
            np.linspace(self.lon_min, self.lon_max, self.grid_size),
            np.linspace(self.lat_max, self.lat_min, self.grid_size)
        )
        # 使用 griddata 进行插值  插值到栅格上
        dbz_grid = griddata(
            (lon, lat), dbz,
            (lon_grid, lat_grid),
            method='linear'
        )
        # 掩盖所有小于0的值
        dbz_grid[dbz_grid < 0] = 0
        # 处理缺失值，可以选择插值后的缺失值为np.nan或其他值
        dbz_grid = np.nan_to_num(dbz_grid, nan=0)  # 将nan替换为-9999，或者其他合适的值
        # 归一化到0-1之间
        max_val = np.max(dbz_grid)
        min_val = np.min(dbz_grid)
        dbz_grid_normalized = (dbz_grid - min_val) / (max_val - min_val)
        # 保存雷达提取的反射率数据到指定的路径
        logger.info("保存雷达数据"+self.filename+".npy到" + self.save_path)
        np.save(os.path.join(self.save_path, self.filename + ".npy"), dbz_grid_normalized)
        return dbz_grid_normalized
